package com.active.test.topic.consumer;

import lombok.extern.slf4j.Slf4j;
import org.apache.activemq.ActiveMQConnectionFactory;

import javax.jms.*;
import java.io.IOException;

/**
 * Created with IntelliJ IDEA.
 * Description:
 *
 * @author lzy
 * @create 2019-08-28 下午2:58
 */
@Slf4j
public class JmsConsumer_Topic {
    private static final String ACTIVEMQ_URL = "tcp://localhost:61616";
    private static final String TOPIC_NAME = "topic-atguigu";

    public static void main(String[] args) throws JMSException, IOException {
        log.info("我是3号消费者");

        //1.创建连接工厂，按照给定的url地址，采用默认用户名和密码
        final ActiveMQConnectionFactory activeMQConnectionFactory = new ActiveMQConnectionFactory(ACTIVEMQ_URL);
        //2.通过连接工厂，获取连接的connection
        final Connection connection = activeMQConnectionFactory.createConnection();
        connection.start();

        //3.创建会话
        // 两个参数，第一个叫事务，第二个叫签收
        final Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);

        //4.创建目的地（具体是队列还是主题）
        final Topic topic = session.createTopic(TOPIC_NAME);

        //5.创建消费者
        final MessageConsumer consumer = session.createConsumer(topic);

        /*
         * 通过监听的方式来消费消息
         */
        consumer.setMessageListener(message -> {
            if (null != message && message instanceof TextMessage) {
                TextMessage textMessage = (TextMessage) message;
                try {
                    log.info("消费者message listener接收到消息：{}", textMessage.getText());
                } catch (JMSException e) {
                    e.printStackTrace();
                }
            }
        });

        // press any key to exit
        System.in.read();

        consumer.close();
        session.close();
        connection.close();
    }
}
